package com.study.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.study.common.AutoIdFactory;
import com.study.model.mdao.PurAppMapper;
import com.study.model.pojo.PurApp;
import com.study.services.PurAppServices;

@RestController
@CrossOrigin
@RequestMapping("/purApp")
public class PurAppController {
	@Autowired
	PurAppServices pas;
	@Autowired
	PurAppMapper pam;

	/***
	 * 添加采购申请
	 * 
	 * @param form
	 * @param table
	 * @return
	 */
	@RequestMapping("/saveApp")
	@ResponseBody
	public JSONObject savePurApp(String form, String table) {
		System.out.println("进入controller");

		JSONObject forms = JSONObject.parseObject(form);
		JSONArray tables = JSONArray.parseArray(table);
		System.out.println("tables---" + tables);

		PurApp app = JSONObject.toJavaObject(forms, PurApp.class);
		System.out.println(app.getTheme());
		// 添加pur_app 申请表
		String atype = "CGSQ";
		String abillcode = pam.findPurAppMaxId();

		AutoIdFactory idFactory = new AutoIdFactory();
		String appid = idFactory.getId(atype, abillcode);
		app.setAppId(appid);
		pas.addPurApp(app);

		// 添加明细表
		String dtype = "SQXQ";
		for (int i = 0; i < tables.size(); i++) {
			String dbillcode = pam.findPurAppDetailMaxId();
			String detailid = idFactory.getId(dtype, dbillcode);
			JSONObject obj = tables.getJSONObject(i);
			Map map = JSONObject.toJavaObject(obj, Map.class);
			map.put("appdetail_id", detailid);
			map.put("app_id", appid);
			System.out.println(map.toString());
			pas.addPurAppDetail(map);

		}

		return (JSONObject) new JSONObject().put("success", "已保存");
	}

	@RequestMapping("/delApp")
	public String delPurApp(String appId) {
		System.out.println("删除的：" + appId);

		pas.delAppDetail(appId);
		pas.delPurApp(appId);
		return "删除成功！";
	}

	@RequestMapping("/select")
	@ResponseBody
	public List<PurApp> selectAll(String theme, String applicant, String appdept, String state) {
		System.out.println(appdept + state);

		List<PurApp> list = pas.findPurAppList(theme, applicant, appdept, state);
		return list;
	}

	/**
	 * 根据id查询单个申请
	 */
	@RequestMapping("/selectById")
	@ResponseBody
	public String selectById(String appId) {
		System.out.println(appId);
		return JSON.toJSONString(pas.findPurAppById(appId));
	}

	@RequestMapping("/updateToOne")
	public String updateToOne(String appId) {
		pas.updateToOne(appId);
		return "已修改状态为待审批";
	}

}
